package com.css.zfzx.sjcj.modules.hddcRock5LinePre.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcRock5LinePre.repository.HddcRock5linepreNativeRepository;
import com.css.zfzx.sjcj.modules.hddcRock5LinePre.repository.HddcRock5linepreRepository;
import com.css.zfzx.sjcj.modules.hddcRock5LinePre.repository.entity.HddcRock5linepreEntity;
import com.css.zfzx.sjcj.modules.hddcRock5LinePre.service.HddcRock5linepreService;
import com.css.zfzx.sjcj.modules.hddcRock5LinePre.viewobjects.HddcRock5linepreQueryParams;
import com.css.zfzx.sjcj.modules.hddcRock5LinePre.viewobjects.HddcRock5linepreVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author zyb
 * @date 2020-11-27
 */
@Service
public class HddcRock5linepreServiceImpl implements HddcRock5linepreService {

	@Autowired
    private HddcRock5linepreRepository hddcRock5linepreRepository;
    @Autowired
    private HddcRock5linepreNativeRepository hddcRock5linepreNativeRepository;

    @Override
    public JSONObject queryHddcRock5linepres(HddcRock5linepreQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcRock5linepreEntity> hddcRock5lineprePage = this.hddcRock5linepreNativeRepository.queryHddcRock5linepres(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcRock5lineprePage);
        return jsonObject;
    }


    @Override
    public HddcRock5linepreEntity getHddcRock5linepre(String id) {
        HddcRock5linepreEntity hddcRock5linepre = this.hddcRock5linepreRepository.findById(id).orElse(null);
         return hddcRock5linepre;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcRock5linepreEntity saveHddcRock5linepre(HddcRock5linepreEntity hddcRock5linepre) {
        String uuid = UUIDGenerator.getUUID();
        hddcRock5linepre.setUuid(uuid);
        hddcRock5linepre.setCreateUser(PlatformSessionUtils.getUserId());
        hddcRock5linepre.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcRock5linepre.setIsValid("1");
        this.hddcRock5linepreRepository.save(hddcRock5linepre);
        return hddcRock5linepre;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcRock5linepreEntity updateHddcRock5linepre(HddcRock5linepreEntity hddcRock5linepre) {
        UpdateUtil.copyNullProperties(hddcRock5linepreRepository.findByUuidAndIsValid(hddcRock5linepre.getUuid(),
                "1"), hddcRock5linepre);
        hddcRock5linepre.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcRock5linepre.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcRock5linepreRepository.save(hddcRock5linepre);
        return hddcRock5linepre;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcRock5linepres(List<String> ids) {
        List<HddcRock5linepreEntity> hddcRock5linepreList = this.hddcRock5linepreRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcRock5linepreList) && hddcRock5linepreList.size() > 0) {
            for(HddcRock5linepreEntity hddcRock5linepre : hddcRock5linepreList) {
                hddcRock5linepre.setIsValid("0");
                hddcRock5linepre.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcRock5linepre.setUpdateTime(new Date());
                this.hddcRock5linepreRepository.save(hddcRock5linepre);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcRock5linepreQueryParams queryParams, HttpServletResponse response) {
        List<HddcRock5linepreEntity> yhDisasterEntities = hddcRock5linepreNativeRepository.exportYhDisasters(queryParams);
        List<HddcRock5linepreVO> list=new ArrayList<>();
        for (HddcRock5linepreEntity entity:yhDisasterEntities) {
            HddcRock5linepreVO yhDisasterVO=new HddcRock5linepreVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"1：5万底图岩体线-线","1：5万底图岩体线-线",HddcRock5linepreVO.class,"1：5万底图岩体线-线.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcRock5linepreVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcRock5linepreVO.class, params);
            List<HddcRock5linepreVO> list = result.getList();
            // Excel条数据
            //int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcRock5linepreVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcRock5linepreVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList(List<HddcRock5linepreVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcRock5linepreEntity yhDisasterEntity = new HddcRock5linepreEntity();
            HddcRock5linepreVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcRock5linepre(yhDisasterEntity);
        }
    }

}
